package year2019.month08;

/**
 * ArrayList简单实现
 * @param <T>
 */
public class MyArrayList<T> {

    private Object[] elementTable;
    private int size=0;

    public MyArrayList(){
        elementTable=new Object[10];
    }

    public MyArrayList(int size){
        if (size>0){
            elementTable = new Object[size];
        } else if (size==0){
            elementTable = new Object[0];
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+ size);
        }
    }

    public boolean add(T element){
        int oldCapacity = elementTable.length;
        if (size>=oldCapacity-1){
            Object[] newElementTable = new Object[oldCapacity+(oldCapacity>>1)];  //每次增长二分之一长度
            System.arraycopy(elementTable,0,newElementTable,0,oldCapacity);
            elementTable=newElementTable;
        }
        elementTable[size++]=element;
        return true;
    }

    public T get(int index){
        return (T) elementTable[index];
    }

    public int size(){
        return size;
    }

    public static void main(String[] args){

//        MyArrayList<String> myArrayList = new MyArrayList<>();
        MyArrayList<String> myArrayList = new MyArrayList<>(100);
        for (int i=1; i<=100; i++){
            myArrayList.add("元素："+i);
        }
        System.out.println(myArrayList.size());
        for (int i=0; i<myArrayList.size(); i++){
            System.out.println(myArrayList.get(i));
        }


    }

}
